package com.yt.ds.chapter4;

import com.yt.ds.io.In;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lzf
 * @Date: 2020/7/29 14:40
 * @Description: 符号图
 */
public class SymbolGraph {
    private Map<String, Integer> map;      // 符号名 -> 索引
    private String[] keys;              // 索引 -> 符号名
    private Graph graph;                // 图

    public SymbolGraph(String stream, String sp) {
        map = new HashMap<>();
        // 第一遍遍历, 为map和keys赋值
        In in = new In(stream);
        while (in.hasNextLine()) {
            String[] a = in.readLine().split(sp);
            for (int i = 0; i < a.length; i++) {
                String str = a[i].trim();
                if (!map.containsKey(str)) {
                    map.put(str, map.size());
                }
            }
        }
        keys = new String[map.size()];
        for (String name : map.keySet()) {
            keys[map.get(name)] = name;
        }
        graph = new UnDigraph(map.size());

        // 第二遍遍历
        in = new In(stream);
        while (in.hasNextLine()) {
            String[] a = in.readLine().split(sp);
            int v = map.get(a[0].trim());
            for (int i = 1; i < a.length; i++) {
                graph.addEdge(v, map.get(a[i].trim()));
            }
        }
    }

    // 是否包含字符串
    public boolean contains(String s) {
        return map.containsKey(s);
    }

    // 名称对应的序号
    public int index(String s) {
        return map.get(s);
    }

    // 序号对应的名称
    public String name(int index) {
        return keys[index];
    }

    // 获取图
    public Graph getGraph() {
        return graph;
    }

}
